package it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;

import org.eclipse.emf.ecore.util.EcoreUtil;

import it.univaq.mancoosi.injectors.systemconfiguration.managers.GroupManager;
import it.univaq.mancoosi.injectors.systemconfiguration.utils.ProcessCommand;
import it.univaq.mancoosi.mancoosimm.Group;
import it.univaq.mancoosi.mancoosimm.User;

public class UbuntuGroupManager extends GroupManager {

	public static GroupManager getInstance(){
		if (INSTANCE == null)
			INSTANCE = new UbuntuGroupManager();
		return INSTANCE;
	}

	@Override
	public void synchronize() throws IOException {
		
		Iterator<Group> iterator = this.groupMap.values().iterator();
		while (iterator.hasNext()) {
			Group curr = iterator.next();
			if (!existsInTheSystem(curr.getName())) {
				this.groupMap.remove(curr);
				EcoreUtil.delete(curr);
			}
		}
	}
	
	public boolean existsInTheSystem (String groupName) {
		try {
			String[] cmd = {"/bin/sh","-c","groupmod "+ groupName};
			BufferedReader input = ProcessCommand.getInstance().getErrorSream(cmd);	

			String line = input.readLine();

			if (line != null && line.contains("does not exist")) return false;
			else return true;
		}
		catch (Exception e) {
			e.printStackTrace();
			return true;
		}
	}

}
